<?php

namespace app\api\controller;

use app\api\BaseController;
use app\api\middleware\Auth;
use app\common\controller\WxPay;
use think\facade\Db;

class UserOne extends BaseController
{
    protected $middleware = [
        Auth::class => ['except' => [''] ]
    ];

    /**
     * 收益明细
     */
    public function walletLog()
    {
        $param = get_params();
        $sql[] = ['uid','=',JWT_UID];
        $sql[] = ['delete_time','=',0];
        $sql[] = ['user_type','=',1];
        if (empty($param['status'])) {
            $sql[] = ['status','=',1];
        } else {
            $sql[] = ['status','=',0];
        }
        $data = Db::name('wallet_log')->where($sql)
            ->order('id desc')->page($param['page'])
            ->limit(10)->select()->toArray();
        if (!empty($data)) {
            foreach ($data as &$val) {
                $val['create_time'] = datetime($val['create_time']);
            }
        }
        return success('',$data);
    }

    /**
     * 提现配置
     */
    public function xianConfig()
    {
        $data = Db::name('config')->where('id',11)->find();
        $conf = unserialize($data['content']);
        $conf['max_money'] = Db::name('user_one')->where('id',JWT_UID)->value('wallet');
        return success('',$conf);
    }
    
    /**
     * 提现提交
     */
    public function withdraw()
    {
        $param = get_params();
        if ($param['money'] <= 0) {
            return error('提现金额不能为0');
        }
        $member = Db::name('user_one')->where('id',JWT_UID)->find();
        $config = Db::name('config')->where('id',11)->find();
        $conf = unserialize($config['content']);
        if ($conf['zd_money'] > $param['money']) {
            return error('最低提现金额'.$conf['zd_money'].'元');
        }

        if ($member['wallet'] < $param['money']) {
            return error('提现金额不足');
        }
        $rate = $param['money']*$conf['rate']*0.01;
        $cha = $param['money'] - $rate;
        $dz_money = round($cha,2);
        $res = Db::name('user_one')->where('id',$member['id'])->dec('wallet',$param['money'])->update();
        if (!$res) {
            return error('发起提现失败');
        }
        Db::name('withdraw')->insert([
            'uid' => $member['id'],
            'money' => $param['money'],
            'tx_type' => 1,
            'dz_money' => $dz_money,
            'rate' => $conf['rate'],
            'create_time' => time()
        ]);
        return success('提交成功');
    }

    /**
     * 提现记录
     */
    public function withdrawLog()
    {
        $param = get_params();
        $sql[] = ['delete_time','=',0];
        $sql[] = ['tx_type','=',1];
        $sql[] = ['uid','=',JWT_UID];
        $data = Db::name('withdraw')
            ->where($sql)
            ->order('id desc')
            ->page($param['page'])
            ->limit(10)
            ->select()->toArray();
        if (!empty($data)) {
            foreach ($data as &$val) {
                $val['create_time'] = datetime($val['create_time']);
                $val['rate'] = round($val['rate'],1).'%';
            }
        }
        return success('',$data);
    }
    
    /**
     * 故障反馈
     */
    public function orderRefund()
    {
        $param = get_params();
        $sql[] = ['o.delete_time','=',0];
        if ($param['status'] == 1) {
            $sql[] = ['o.status','=',2];
            $sql[] = ['o.sh_status','=',1];
        } else {
            $sql[] = ['o.status','=',3];
        }
        $sql[] = ['d.user_one','=',JWT_UID];
        $data = Db::name('order')->alias('o')
                ->join('device d','o.device_id=d.id')
                ->join('user_one u','d.user_one=u.id')
                ->field('o.id,o.order_no,o.wine_name,o.wine_num,o.amount,o.sh_title,o.status,o.sh_status')
                ->where($sql)
                ->order('o.id desc')
                ->page($param['page'])
                ->limit(10)
                ->select()
                ->toArray();
        return success('',$data);
    }

    /**
     * 故障反馈处理
     */
    public function examine()
    {
        $param = get_params();
        $data = Db::name('order')->where('id',$param['id'])->find();
        if (empty($data)) {
            return error('未找到该记录');
        }
        if ($data['status'] != 1) {
            return error('该提现已处理');
        }
        $save['update_time'] = time();
        if ($param['type'] == 1) {
            $save['status'] = 2;
            //原路退回账户
            if ($data['pay_type'] == 1) {
                $user = Db::name('user')->where('id',$data['uid'])->find();
                $wx = new WxPay();
                $refund_notify_url = request()->domain()."/api/notify/backTeamPayResult";
                $back = [
                    'order_no' => $data['order_no'],
                    'out_found_no' => $data['out_found_no'],
                    'amount' => $data['amount']
                ];
                $wx->refund($back,$user['openid'],$refund_notify_url);
            }
            if ($data['pay_type'] == 2) {
                Db::name('user')->where('id',$data['uid'])->inc('score',floatval($data['amount']))->update();
                Db::name('score_log')->insert([
                    'uid' => $data['uid'],
                    'title' => '订单退款',
                    'type' => 1,
                    'num' => $data['amount'],
                    'create_time' => time(),
                ]);
            }
        } else {
            $save['status'] = 3;
            if (!empty($param['refuse'])) {
                $save['refuse'] = $param['refuse'];
            }
        }
        Db::name('order')->where('id',$param['id'])->update($save);
        return success('操作成功');
    }

    /**
     * 详情
     */
    public function orderDetail()
    {
        $param = get_params();
        $data = Db::name('order')->where('id',$param['id'])->find();
        $data['device'] = Db::name('device')->where('id',$data['device_id'])->find();
        $data['address'] = json_decode($data['address'],true);
        if (!empty($data['recharge_info'])) {
            $data['recharge_info'] = json_decode($data['recharge_info'],true);
        }

        $data['create_time'] = datetime($data['create_time']);
        $data['pay_time'] = datetime($data['pay_time']);
        if (!empty($data['sh_img'])) {
            $data['sh_img'] = explode(',',$data['sh_img']);
        }
        if (!empty($data['update_time'])) {
            $data['update_time'] = datetime($data['update_time']);
        }
        if (!empty($data['sh_time'])) {
            $data['sh_time'] = datetime($data['sh_time']);
        }
        return success('',$data);
    }

    /**
     * 我的兑酒券
     */
    public function couponList()
    {
        $param = get_params();
        $sql[] = ['uid','=',JWT_UID];
        $sql[] = ['user_type','=',2];
        $sql[] = ['delete_time','=',0];
        $sql[] = ['status','=',$param['status']];
        $data = Db::name('coupon_log')->where($sql)
            ->order('id desc')
            ->page($param['page'])
            ->limit(10)
            ->select()
            ->toArray();
        if (!empty($data)) {
            foreach ($data as &$val) {
                $val['end_time'] = date('Y-m-d',$val['end_time']);
            }
        }
        return success('',$data);
    }

    /**
     * 立即兑换
     */
    public function toDui()
    {
        $param = get_params();
        if (empty($param['device_id'])) {
            return error('请选择设备');
        }
        $couponLog = Db::name('coupon_log')->where('id',$param['coupon_id'])->find();
        if ($couponLog['status'] != 1) {
            return error('当前兑酒券已使用');
        }
        $device = Db::name('device')->alias('d')
            ->join('cate c','d.cate_id=c.id')
            ->field('d.*,c.title as cate_name')
            ->where('d.id',$param['device_id'])
            ->find();
        if (empty($device)) {
            return error('未找到设备信息');
        }
        if ($device['status'] != 'run') {
            return error('设备故障');
        }
        if ($device['weight'] < $couponLog['nums']) {
            return error('当前设备酒量不足');
        }
        $shop = Db::name('user_one')->field('id,user_name,mobile,address')
            ->where('id',$device['user_one'])->find();
        $insert = [
            'uid' => JWT_UID,
            'coupon_id' => $param['coupon_id'],
            'device_id' => $param['device_id'],
            'wine_num' => $couponLog['nums'],
            'wine_name' => $device['cate_name'],
            'order_no' => date('YmdHis').rand(1000,9999),
            'out_found_no' => 'BK'.date('YmdHis').rand(100,999),
            'address' => json_encode($shop,JSON_UNESCAPED_UNICODE),
            'status' => 1,
            'pay_status' => 1,
            'pay_type' => 3,
            'order_type' => 2,
            'create_time' => time(),
            'pay_time' => time(),
        ];
        //服务器下发订单预创建信息
        $work = new Work();
        $topic = 'liquor/s/'.$device['imei'].'/order';
        //服务器下发订单创建信息
        $msg = json_encode([
            "orderNum" => $insert['order_no'],
            "weight" => $insert['wine_num'],
            "msgId" => $device['msgId'],
            "type"  => "create"
        ]);
        $work->preOrder($topic,$msg);
        $orderId = Db::name('order')->insertGetId($insert);
        Db::name('coupon_log')->where('id',$param['coupon_id'])->update(['status'=>2,'update_time'=>time()]);
        //服务器下发订单支付成功信息
        $msg = json_encode([
            "orderNum" => $insert['order_no'],
            "weight" => $insert['wine_num'],
            "msgId" => $device['msgId'],
            "type"  => "pay"
        ]);
        $work->preOrder($topic,$msg);
        return json(['code'=>0,'msg'=>'支付成功','data'=>['order_id'=>$orderId]]);
    }

    /**
     * 我的设备
     */
    public function myDevice()
    {
        $param = get_params();
        $sql[] = ['d.user_one','=',JWT_UID];
        $sql[] = ['d.delete_time','=',0];
        $deviceList = Db::name('device')->alias('d')
            ->join('user_one u','d.user_one=u.id')
            ->field('d.*,u.mobile,u.address')
            ->where($sql)
            ->order('d.id desc')
            ->page($param['page'])
            ->limit(10)
            ->select()
            ->toArray();
        if (!empty($deviceList)) {
            $config = Db::name('config')->where('id',10)->find();
            $conf = unserialize($config['content']);
            foreach ($deviceList as &$val) {
                $val['device_img'] = $conf['device_img'];
            }
        }
        return success('',$deviceList);
    }

    /**
     * 设备详情
     */
    public function deviceDetail()
    {
        $param = get_params();
        $device = Db::name('device')->alias('d')
            ->join('user_one u','d.user_one=u.id')
            ->field('d.*,u.mobile,u.address,u.lng,u.lat')
            ->where('d.id',$param['id'])
            ->find();
        if (empty($device)) {
            return error('未找到设备信息');
        }
        $device['cate_name'] = Db::name('cate')->where('id',$device['cate_id'])->value('title');
        $config = Db::name('config')->where('id',10)->find();
        $conf = unserialize($config['content']);
        $device['device_detail_img'] = $conf['device_detail_img'];
        //已售多少升
        $device['wine_num'] = Db::name('order')->alias('o')
            ->join('device d','o.device_id=d.id')
            ->where(['o.device_id'=>$device['id'],'o.status'=>1])
            ->sum('o.wine_num');

        //收益多少
        $device['order_amount'] = Db::name('wallet_log')->alias('w')
            ->join('order o','w.order_id=o.id')
            ->join('device d','o.device_id=d.id')
            ->where(['o.device_id'=>$device['id'],'w.status'=>1,'w.user_type'=>3,'o.status'=>1,'d.user_three'=>JWT_UID])
            ->sum('w.num');
        return success('',$device);
    }

    /**
     * 收益统计
     */
    public function usage()
    {
        $param = get_params();
        $days = [];
        if ($param['type'] == 1) {
            //近5天数据
            $days = dateFive();
            foreach ($days as &$val) {
                $start_time = strtotime($val['dates'].' 00:00:00');
                $end_time = strtotime($val['dates'].' 23:59:59');
                $val['date'] = date('m.d',$val['time']);
                //收益
                $val['money'] = Db::name('wallet_log')
                    ->where([['uid','=',JWT_UID],['user_type','=',1],['status','=',1],['create_time','between',[$start_time,$end_time]]])
                    ->sum('num');
            }
        }
        if ($param['type'] == 2) {
            //近5月数据
            $days = dateFiveMonth();
            foreach ($days as &$val) {
                $start_time = strtotime($val['start_date'].' 00:00:00');
                $end_time = strtotime($val['end_date'].' 23:59:59');
                $val['date'] = date('m月',$val['time']);
                //收益
                $val['money'] = Db::name('wallet_log')
                    ->where([['uid','=',JWT_UID],['user_type','=',1],['status','=',1],['create_time','between',[$start_time,$end_time]]])
                    ->sum('num');
            }
        }
        if ($param['type'] == 3) {
            //近5年数据
            $days = dateFiveYear();
            foreach ($days as &$val) {
                $start_time = strtotime($val['start_date'].' 00:00:00');
                $end_time = strtotime($val['end_date'].' 00:00:00');
                $val['date'] = date('Y年',$val['time']);
                //收益
                $val['money'] = Db::name('wallet_log')
                    ->where([['uid','=',JWT_UID],['user_type','=',1],['status','=',1],['create_time','between',[$start_time,$end_time]]])
                    ->sum('num');
            }
        }
        $reversedArray = array_reverse($days);
        $finalArray = array_map('array_reverse', $reversedArray);
        return success('',$finalArray);
    }

    /**
     * 购酒记录
     */
    public function orderLog()
    {
        $param = get_params();
        $sql[] = ['o.delete_time','=',0];
        $sql[] = ['o.status','>',0];
        $sql[] = ['d.user_one','=',JWT_UID];
        if (!empty($param['keys'])) {
            $sql[] = ['o.order_no','like',"%{$param['keys']}%"];
        }
        $data = Db::name('order')->alias('o')
            ->join('device d','o.device_id=d.id')
            ->join('user_one u','d.user_one=u.id')
            ->field('o.id,o.uid,o.order_no,o.wine_name,o.wine_num,o.amount,o.sh_title,o.status,o.sh_status,o.order_type,o.pay_time')
            ->where($sql)
            ->order('o.id desc')
            ->page($param['page'])
            ->limit(10)
            ->select()
            ->toArray();
        if (!empty($data)) {
            foreach ($data as &$val) {
                if ($val['order_type'] == 1) {
                    $val['nickname'] = Db::name('user')->where('id',$val['uid'])->value('nickname');
                } else {
                    $val['nickname'] = Db::name('user_one')->where('id',$val['uid'])->value('user_name');
                }
                $val['pay_time'] = datetime($val['pay_time']);
            }
        }
        return success('',$data);
    }
}